package main.java.pers.seg.model.utils;

import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Iterator;

public class ListUtils {

    public static ArrayList activityList = new ArrayList();

    public static void print(){
        for(int i=0;i<activityList.size();i++){
            System.out.println(activityList.get(i));
        }
    }

    /**
     * 保存activity的index
     * 暂且只把Activity，OtherWindow，Fragment，Dialog和menu放入activityList.（并不能把所有的Screen都放入）
     * @param gatornode
     */
    public static void scanActivity(Element gatornode) {
        //首先获取当前节点的所有属性节点
        if (gatornode.getName().equals("Activity") || gatornode.getName().equals("OtherWindow")
                || gatornode.getName().equals("Fragment")) {
            activityList.add(gatornode.attributeValue("name"));
        }
        if(gatornode.getName().equals("Dialog")){
            activityList.add(gatornode.attributeValue("name")+" "+gatornode.attributeValue("allocMethod"));
        }
        //menu
        if (gatornode.getName().equals("View")
                && gatornode.attributeValue("type").equals("android.view.Menu")
                && gatornode.getParent().getName().equals("GUIHierarchy")) {
            //通过type+source唯一确定
            activityList.add("android.view.Menu" + " " + gatornode.attributeValue("source"));
        }

        Iterator<Element> gatoriterator = gatornode.elementIterator();

        while(gatoriterator.hasNext()){
            Element e = gatoriterator.next();
            scanActivity(e);
        }
    }

    public static int getIndex(String target){
        int i;
        String[] arr = target.split("alloc: ");
        String[] dialog = arr[0].split("DIALOG\\[|\\]");

        String[] transfer = target.split("\\[|\\]");
        //针对Dialog情况
        if(arr.length>1){
            for(i=0;i<activityList.size();i++){
                if((dialog[1]+" "+arr[1]).equals(activityList.get(i).toString())){
                    break;
                }
            }
        }
        else{
            if(transfer.length>1){
                for(i=0;i<activityList.size();i++){

                    if(transfer[1].equals(activityList.get(i))){
                        break;
                    }
                }
            }else{
                for(i=0;i<activityList.size();i++){
                    if(target.equals(activityList.get(i))){
                        break;
                    }
                }
            }

        }
        return i;
    }

    public static int getActivity(String activity){
        int i;
        for(i=0;i<activityList.size();i++){
            if(activityList.get(i).toString().equals(activity)){
                break;
            }
        }
        return i;
    }
}
